﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Enterprise.RelationQuery
{
    public partial class CompanyMaintain : BasePage
    {
        IBLL_Company IBC = Factory.BLL_Company();
        IBLL_ProcurementBasic ipb = Factory.BLL_ProcurementBasic();
        public string currentID="";
        //public CompanyMaintain()
        //{
        //    this.ModuleNo = Module.配送关系管理.ToString();
        //    this.PageOperateType = OperateType.配送关系审核.ToString();
        //}

        protected void Page_Load(object sender, EventArgs e)
        {
            currentID = CurrentAccount.GetUser().Org.OrgID;
            if (!this.IsPostBack)
            {
                //绑定所有项目
                ProcurementProject procurementProject = new ProcurementProject();
                procurementProject.ProcureStartTimeFrom = Convert.ToDateTime("1890-01-01");
                procurementProject.ProcureStartTimeTo = Convert.ToDateTime("2099-12-31");
                procurementProject.ProcureEndTimeFrom = Convert.ToDateTime("2000-01-01");
                procurementProject.ProcureEndTimeTo = Convert.ToDateTime("2099-12-31");
                int temp;
                IList<ProcurementProject> projectList = ipb.GetProjectByWhere(procurementProject, 1, 0, out temp);
                ddlProject.DataSource = projectList;
                ddlProject.DataTextField = "ProjectName";
                ddlProject.DataValueField = "ProjectID";
                ddlProject.DataBind();
                ViewState["ProjectId"] = ddlProject.SelectedValue;
                //ListItem item = new ListItem();
                //item.Text = Constants.ALL_ITEM_TEXT;
                //item.Value = Constants.ALL_ITEM_VALUE;
                //ddlProject.Items.Insert(0, item);
                if (CurrentAccount.GetUser().UserRole.RoleID == "05")
                {
                    lblNav.Text = "<ul><li class=\"active\"><a href=\"javascript:void(0);\">配送企业管理</a></li><li><a href=\"RelationQueryUnpack.aspx\">配送产品管理</a></li><li><a href=\"DistributionRelationToQuery.aspx\">配送关系查询</a></li></ul>";

                    CompanyBind();
                }
                else
                {
                    HZ.DrugTrade.Model.Query.Company com = new HZ.DrugTrade.Model.Query.Company();
                    com.CompanyID = currentID; 
                    int outINt = 0;
                    IList<Company> lst = IBC.GetCompanyByWhere(com, 1, 1, out outINt);

                    if (lst != null && lst[0].CompanyType == EnumCompanyType.配送企业)
                    {
                        this.btnAdd.Visible = false;
                        this.btnQuery.Enabled = false;
                    }
                    else
                    {
                        lblNav.Text = "<ul><li class=\"active\"><a href=\"javascript:void(0);\">配送企业管理</a></li><li><a href=\"RelationQueryUnpack.aspx\">配送产品管理</a></li><li><a href=\"DistributionRelationToQuery.aspx\">配送关系查询</a></li><li><a href=\"DistributionRelationToConfirm.aspx\">配送关系确认</a></li></ul>";
                        CompanyBind();
                    }
                }
            }
        }

        /// <summary>
        /// 绑定角色列表
        /// </summary>
        private void CompanyBind()
        {

            string strWhere = "";

            if (string.IsNullOrEmpty(new HZ.Common.ConvertHelper(txtReturnlName.Text.Trim()).String) == false)
            {
                strWhere += " and  tb_companyinfo.CompanyName like '%" + new HZ.Common.ConvertHelper(txtReturnlName.Text.Trim()).String + "%'";
            }
            if (string.IsNullOrEmpty(DllType.SelectedItem.Value.Trim()) == false)
            {
                strWhere += " and  CompanyType =" + DllType.SelectedItem.Value.Trim();
            }
            //if (string.IsNullOrEmpty(this.DllArea.SelectedValue))
            //{
            //    //strWhere += "  and len(AreaIDs)>80 ";
            //}
            if (this.DllArea.SelectedValue=="-1")
            {
                strWhere += " and TB_Company.CompanyID in (select companyPS_Id from TB_PSSelectArea where checkByZbzx=1)";
            }
            else
            {
                strWhere += " and TB_Company.CompanyID in (select companyPS_Id from TB_PSSelectArea where checkByZbzx=1 and  areaId like '%" + DllArea.SelectedItem.Value + "%')"; 
                    //AreaIDs like '%" + DllArea.SelectedItem.Value + "%' " 注释 by zdc
            }
            if (string.IsNullOrEmpty(new HZ.Common.ConvertHelper(txtBusinessCertificate.Text.Trim()).String) == false)
            {
                strWhere += " and  tb_companyinfo.BusinessCertificate like '%" + new HZ.Common.ConvertHelper(txtBusinessCertificate.Text.Trim()).String + "%'";
            }
            strWhere += "  and companytype != 3 " + (ddlProject.SelectedItem.Value == "0002" ? "and ishcygcg in(1,2)" : ddlProject.SelectedItem.Value == "0001" ? "and (ishcygcg is null or ishcygcg = 2)" : "") + " or TB_Company.companyid in (select companyid_ps from tb_company where companyid = '" + CurrentAccount.GetUser().UserID + "') " + (ddlProject.SelectedItem.Value == "0002" ? "and ishcygcg in(1,2)" : ddlProject.SelectedItem.Value == "0001" ? "and (ishcygcg is null or ishcygcg = 2)" : "");
            strWhere += " order by   tb_companyinfo.CompanyName ";
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalrecord = 0;
            this.gvwCompnayist.DataSource = IBC.GetCompanyInfoByWhereZDC(strWhere, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalrecord);
            this.gvwCompnayist.DataBind();
            this.AspNetPager1.RecordCount = totalrecord;
        }

        /// <summary>
        /// 新增角色及权限,转向新页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            this.Response.Redirect("CompanyAdd.aspx");
        }

        /// <summary>
        /// 根据角色编号删除角色及相应的权限信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwRoleList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Del"))
            {
                Company Comy = new Company();
                string strCompanyID = e.CommandArgument.ToString();
                Comy.CompanyID = strCompanyID;
                int intRtn = IBC.DeleteCompany(Comy);
                if (intRtn == 0)
                {
                    PageError("删除失败！", "");
                }
                if (intRtn == 1)
                {
                    CompanyBind();
                    PageInfo("删除成功！", "");
                }
            }
            else if (e.CommandName.Equals("Dist"))
            {
                Response.Redirect("DistributionRelationWithWizard.aspx?PID=" + e.CommandArgument.ToString().Split('|')[0] + "&ishcygcg=" + e.CommandArgument.ToString().Split('|')[1] + "&ProjectId=" + ViewState["ProjectId"] + "");
            }
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //gvwCompnayist.EditIndex = e.NewEditIndex;
            //CompanyBind();

            GridViewRow r = gvwCompnayist.Rows[e.NewEditIndex];
           string CompanyID = Convert.ToString(gvwCompnayist.DataKeys[e.NewEditIndex].Value);


           Response.Redirect("RegCompanyAndAreaEdit.aspx?companyId=" + CompanyID);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            GridViewRow r = gvwCompnayist.Rows[e.RowIndex];
            Company Comy = new Company();

            Comy.CompanyID = Convert.ToString(gvwCompnayist.DataKeys[e.RowIndex].Value);
            Comy.CompanyType = EnumParse.GetCompanyType(((Label)gvwCompnayist.Rows[e.RowIndex].FindControl("lblCompanyType")).Text.Trim());
            if (!string.IsNullOrEmpty(((TextBox)gvwCompnayist.Rows[e.RowIndex].FindControl("txtCompanyName")).Text.Trim()))
            {
                Comy.CompanyName = ((TextBox)gvwCompnayist.Rows[e.RowIndex].FindControl("txtCompanyName")).Text.Trim();
            }
            else
            {
                HZ.Web.WebUtil.Alert("企业名称不能为空！", this);
                ((TextBox)gvwCompnayist.Rows[e.RowIndex].FindControl("txtCompanyName")).Focus();
                return;
            }

            bool flag = IBC.UpdateCompany(Comy);
            if (flag)
            {
                PageInfo("更新成功！", "");
            }
            else
            {
                HZ.Web.WebUtil.Alert("更新失败！该名称已被其他企业占用。", this);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvwCompnayist.EditIndex = -1;
            CompanyBind();
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            CompanyBind();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
            CompanyBind();
            ViewState["ProjectId"] = ddlProject.SelectedValue;
        }
        /// <summary>
        /// 绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Company c = e.Row.DataItem as Company;
                if (e.Row.FindControl("RadioButtonList1") != null)
                {
                    RadioButtonList rbl = e.Row.FindControl("RadioButtonList1") as RadioButtonList;
                    rbl.Items[0].Selected = c.CompanyType == EnumCompanyType.生产企业;
                    rbl.Items[1].Selected = c.CompanyType == EnumCompanyType.经营企业;
                    rbl.Items[2].Selected = c.CompanyType == EnumCompanyType.配送企业;
                }

            }
        }

        protected void btnAdd_Click1(object sender, EventArgs e)
        {
            //
            Response.Redirect("RegCompanyAndArea.aspx");
            //HZ.Web.WebUtil.RedirectByScript("CompanyAdd.aspx");
        }

        /// <summary>
        /// 返回企业名称列输出，配送企业加上查看信息链接，非配送企业直接输出名称
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="companyName"></param>
        /// <param name="companyType"></param>
        /// <param name="companyType"></param>
        /// <returns></returns>
        protected string GetCompanyRender(string companyId, string companyName, int companyType)
        {
            if (companyType !=1)
            {
                return "<a href=\"javascript:void(0)\"  title=\"查看配送企业详细信息\" onclick=\"window.open('../../CommonPage/CompanyInfo.aspx?companyid=" + companyId + "','selectCompany','width=550,height=350,resizable=0,scrollbars=0, status=0, toolbar=0, menubar=0')\" >" + companyName + "</a>";
            }
            else
            {
                return companyName;
            }
        }

        /// <summary>
        /// 将给定的url加上script 实现页面跳转
        /// 针对button 的 onclintclick 新窗口打开
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        protected string OpenURLScript(string str)
        {
            int index = str.IndexOf("?");
            //给url加returnUrl,值为当前页面的Url
            if (index != -1)
            {
                str += "&" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            else
            {
                str += "?" + Constants.QUERYSTRING_RETURN_URL + "=" + Page.Request.RawUrl;
            }
            string strScript = "if(!this.disabled){window.open('" + str + "');} return false;";
            return strScript;
        }

    }
}